package kummer.wu;

import java.io.File;
import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.Prediction;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.TextView;

public class KUDictActivity extends Activity implements SoundPool.OnLoadCompleteListener {
	public String dicFile()
	{
		String f = "/sdcard/english/dict.dat";
		File ff = new File(f);
		if(ff.exists())
		{
			return f;
		}
		
		return "/data/data/kummer.wu/files/dict.dat";
	}
	public  String recFile()
	{
		String f = "/sdcard/english/dict.rec";
		File ff = new File(f);
		if(ff.exists())
		{
			return f;
		}
		
		return "/data/data/kummer.wu/files/dict.rec";
	}
	
    /** Called when the activity is first created. */
	WebView myweb;
	//Button btRem;
	//Button btNoRem;
	Teacher teacher;
	//EditText txtPhonetic;
	TextView txtEng;
	TextView txtPho2;
	Typeface tf ;
	TextView txtInfo;

	private GestureOverlayView gestureOverlayView;  
	private GestureLibrary mLibrary;  
	boolean state;

	SoundPool sound;
	int 	  soundID = 0;
	private void loadSound(String file)
	{
		if(soundID!=0)
		{
			sound.unload(soundID);
			soundID = 0;
		}
		File f = new File(file);
		if(f.exists())
		{
			soundID = sound.load(file, 1);
		}
		else
		{
			soundID = 0;
		}
	}
	public void onLoadComplete(SoundPool soundPool,int sampleID,int status)
	{
		if(status==0)
		{
			soundPool.play(sampleID, 1.0f, 1.0f, 0, 0, 1.0f);
		}
	}
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myweb = (WebView)findViewById(R.id.webView1);
        myweb.getSettings().setJavaScriptEnabled(true);  
        myweb.setFocusable(false);
        gestureOverlayView = (GestureOverlayView)findViewById(R.id.gestureOverlayView1);
        mLibrary = GestureLibraries.fromRawResource(this, R.raw.gestures);  
        state = mLibrary.load();
        gestureOverlayView.addOnGesturePerformedListener(new GestureListener()); 
        gestureOverlayView.setGestureVisible(false);
        //btRem= (Button)findViewById(R.id.bt_Rem);
        //btNoRem= (Button)findViewById(R.id.bt_NoRem);
         
        tf = Typeface.createFromAsset(this.getAssets(),  "fonts/segoeui.ttf");
        
        //txtPhonetic = (EditText)findViewById(R.id.editText1);
        //txtPhonetic.setTypeface(tf);
        
        txtEng = (TextView)findViewById(R.id.textView2);
        txtPho2 = (TextView)findViewById(R.id.textView1);
        txtPho2.setTypeface(tf);
        txtInfo = (TextView)findViewById(R.id.textView3);
        
        sound = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 0);
        sound.setOnLoadCompleteListener(this);
        
        
        teacher = new Teacher();
        try {
			teacher.init(dicFile(), recFile());
		} catch (Exception e) {
			e(e.getMessage());
		}
        showCurWord();
    }

	private final class GestureListener implements GestureOverlayView.OnGesturePerformedListener{  
	        public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {  
	            if(state){  
	                List<Prediction> predictions = mLibrary.recognize(gesture);//从手势库中查询匹配的内容，匹配的结果可能包括多个相似的结果，匹配度高的结果放在最前面   
	                if(!predictions.isEmpty()){  
	                    Prediction prediction = predictions.get(0);  
	                    //prediction的score属性代表了与手势的相似程度   
	                   //prediction的name代表手势对应的字母   
	                    if(prediction.score > 1){
	                    	if(prediction.name.equalsIgnoreCase("yes")) 
	                    	{
	                    		recite(false); //todo 临时手势库是个反的
	                    	}
	                    	else if(prediction.name.equalsIgnoreCase("no"))
	                    	{
	                    		recite(true);
	                    	}
	                    	else
	                    	{
	                    		//todo:play sound
	                    	}
	                    }  
	                }  
	            }  
	        }  
	    }  


	
    public String buildHtml(Word w)
    {
    	if(w==null)
    	{
    		return "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></head><body>完成!</body></html>";
    	}
    	else
    	{
    		String s = w.Chinese.replace("<script type='text/javascript'>", "<script type='text/javascript'> 	function switchItem() 	{		if(dd1.style.display=='block'){chgItem(1);} 		else {chgItem(0);} 	}");
    		s = s.replace("padding:0 0 1.75em 1em;", "padding:0 0 0 0;");
	    	return s.replace("<body font-family: 'segoepr'", "<body font-family: 'segoepr' onclick='switchItem()'");
    	}
    }
    public void e(String e)
    {
    	myweb.loadData(e, "text/html", "utf-8");
    }
    public void showCurWord()
    {
    	Word w = null;
    	if(teacher == null)
    	{
    		e("teacher is null");
    	}
		try {
			w = teacher.getCurrentWord();
			
			if(w!=null)
			{
				//loadSound(w.getSoundFile());
				
				
				String inf= buildHtml(w);
				txtEng.setText(w.English);
				txtPho2.setText(w.Phonetic);
				txtInfo.setText(teacher.getCurrentWordInfo());
		    	myweb.loadDataWithBaseURL(null,inf, "text/html","utf-8",null);
		    	
			}
		} catch (IOException e) {
			e(e.getMessage());
		}
    	
    	
    	
    }
    public void recite(boolean rem)
    {
    	if(teacher == null)
    	{
    		e("teacher is null");
    	}
    	try
    	{
    		teacher.recite(rem);
    		showCurWord();
    	}
    	catch(Exception e)
    	{
    		
    	}
    }
}